<template>
<div class="tutoring-container" >
    <div class="tutoring-grid" v-loading="loading">
      <TutoringItem
        v-for="item in tutoringList"
        :key="item.id"
        :tutorInfo="item"
        @onBook="handleBook"
      />
      <TutoringPay 
        :payLoading="payLoading" 
        :tutorInfo="tutorInfoCurrent" 
        :visible="showPayModal" 
        @update:visible="showPayModal = $event" 
        @onPay="handlePay"
      ></TutoringPay>
    </div>
    <div class="pagination-container">
      <Pagination
        :current-page="page" 
        :page-size="rows" 
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <div class="pay-container" v-if="showPayCodeModal">
      <div class="modal-content">
        <div class="modal-header">
          <div class="modal-title">微信支付</div>
          <span class="close-btn" @click="handleClose">×</span>
        </div>
        <div class="modal-body">
          <div class="modal-body-content">
            <img :src="qrCodeDataUrl" />
            <div class="modal-body-content-text" v-if="orderStatus === 2">
              未支付成功，订单已关闭
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <div class="modal-footer-content">
            <div class="modal-footer-content-item">
              扫描二维码完成支付
            </div>
            <div class="modal-footer-content-price">
              ￥{{ payAmount }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script setup>
import { ref, onMounted, unref, onBeforeUnmount } from "vue";
import TutoringItem from "./TutoringItem";
import TutoringPay from "./TutoringPay.vue";
import { myOneToOneList } from "@/service/personalCenter";
import Pagination from "@/components/Pagination";
import { myOrderAdd, myOrderDetail } from "@/service/personalCenter";
import QRCode from 'qrcode';
import { useRouter } from 'vue-router';
import { usePaymentStore } from "@/stores/Payment";

const showPayModal = ref(false)
const tutorInfoCurrent=ref( )
const tutoringList=ref([])
const page=ref(1)
const rows=ref(10)
const total=ref(0)
const loading=ref(false)
const payLoading=ref(false)
const showPayCodeModal=ref(false)
const qrCodeDataUrl = ref('')
const payAmount = ref(0)
const orderId = ref('')
const pollTimer = ref(null)
const orderStatus=ref(3)
const router = useRouter();
const paymentStore = usePaymentStore();
onMounted(()=>{
  getTutoringList();
})

const getTutoringList = () => {
  const params={
    page: unref(page),
    rows: unref(rows)
  }
  loading.value = true;
  myOneToOneList(params).then(res=>{
    console.log(res,'res')
    if(res.data.result.length > 0) {
      res.data.result.map((item) => {
        item.keywords=item.keywords.split(',')
      })
    }
    tutoringList.value = res.data.result;
    total.value = res.data.totalCount;
    loading.value = false;
  })
}

const handleBook = (tutorInfoTemp) => {
  console.log(tutorInfoTemp, 'tutorInfoTemp');
  // debugger
  tutorInfoCurrent.value=tutorInfoTemp;
  showPayModal.value = true
 
}

const handlePay = (payInfo) => {
  console.log(payInfo, 'payInfo')
  // 将支付信息存储到Pinia store中
  paymentStore.setPayInfo({
    ...payInfo,
    tutorInfo: tutorInfoCurrent.value
  });
  
  // 跳转到integralPay页面
  router.push('/integralPay');
  
  // 以下是原有的支付逻辑，现在暂时注释掉
  // payAmount.value = payInfo.totalAmount || 0;
  // const params={
  //   goodsid: tutorInfoCurrent.value.id,
  //   number: payInfo.hours,
  //   appoint_time: payInfo.selectedTime,
  //   origin: 1,
  //   payway: 2, // 1.支付宝，2.微信，3.积分兑换
  //   type: 3,
  //   point: 0
  // }
  // payLoading.value = true
  // myOrderAdd(params).then(res=>{
  //   console.log(res,'res')
  //   if(res.code === '000000') {
  //     payLoading.value = false;
  //     showPayModal.value = false;
      
  //     // 存储订单ID用于轮询
  //     if (res.data && res.data.id) {
  //       orderId.value = res.data.id;
  //     }
      
  //     // 假设接口返回的微信支付URL在res.data.url中
  //     if (res.data && res.data.url) {
  //       // 生成二维码
  //       QRCode.toDataURL(res.data.url, { width: 200 })
  //         .then(url => {
  //           qrCodeDataUrl.value = url;
  //           showPayCodeModal.value = true;
  //           // 开始轮询订单状态
  //           startPollOrderStatus();
  //         })
  //         .catch(err => {
  //           console.error('生成二维码失败:', err);
  //         });
  //     }
  //   }
  // })
}

// 轮询订单状态
const startPollOrderStatus = () => {
  // 清除可能存在的定时器
  if (pollTimer.value) {
    clearInterval(pollTimer.value);
  }
  
  // 设置轮询间隔，每2秒查询一次
  pollTimer.value = setInterval(() => {
    if (!orderId.value || !showPayCodeModal.value) {
      clearInterval(pollTimer.value);
      return;
    }
    
    checkOrderStatus();
  }, 2000);
}

// 检查订单状态
const checkOrderStatus = () => {
  myOrderDetail({ id: orderId.value }).then(res => {
    console.log('订单状态:', res);
    if (res.code === '000000') {
      // 假设 status === 1 表示支付成功
      if (res.data && res.data.status === 2) {
        // 支付成功，停止轮询
        orderStatus.value = 2;
        // clearInterval(pollTimer.value);
        // // 关闭支付码弹窗
        // showPayCodeModal.value = false;
        // ElMessage.success('支付成功');
        // 提示用户支付成功并刷新数据
        // 可以选择刷新列表
        // getTutoringList();
      } else if (res.data && res.data.status === 3) {
        orderStatus.value = 3;
      }
    }
  }).catch(err => {
    console.error('查询订单状态失败:', err);
  });
}

const handleCurrentChange = (newPage) => {
  page.value = newPage;
  getTutoringList();
}

const handleSizeChange = (newSize) => {
  rows.value = newSize;
  getTutoringList();
}

const handleClick = (item) => {
  console.log('点击项目：', item)
}

const handleClose = () => {
  showPayCodeModal.value = false;
  if (pollTimer.value) {
    clearInterval(pollTimer.value);
  }
}

onBeforeUnmount(() => {
    if (pollTimer.value) {
      clearInterval(pollTimer.value);
    }
});
</script>
<style lang="scss" scoped>
.tutoring-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tutoring-grid {
  display: flex;
  flex-wrap: wrap;
  // grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 8px;
  
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.pay-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  .modal-content {
    width: 308px;
    height: 371px;
    background: #fff;
    border-radius: 10px;
    margin: 0 auto;
    box-shadow: 0 4px 20px 0 #219FC71C;
    padding: 20px;
  }
  .modal-header {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .modal-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
    .close-btn {
        font-size: 24px;
        cursor: pointer;
        color: #999;
        position: absolute;
        right: 0;
        top: 0;
        line-height: 0px;
    }
  }
  .modal-body {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 20px;
    .modal-body-content {
      width: 200px;
      height: 200px;
      position: relative;
      img {
        width: 100%;
        height: 100%;
      }
      .modal-body-content-text {
        width: 200px;
        height: 200px;
        font-size: 16px;
        color: #333;
        margin-top: 20px;
        font-weight: 400;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 99999;
        background: rgba(0, 0, 0, 0.3);
        color: #fff;
      }
    }
  }
  .modal-footer {
    
  }
  .modal-footer-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
  }
  .modal-footer-content-item {
    font-size: 16px;
    color: #333;
    margin-top: 20px;
    font-weight: 400;
  }
  .modal-footer-content-price {
    font-size: 24px;
    color: #E52121;
    margin-top: 10px;
  }
}
</style>